package com.qt.eurekaclientuser.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qt.eurekaclientuser.dao.ProductRepository;
import com.qt.eurekaclientuser.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * Despription:
 *
 * @Autor: xusl
 * @Date: 2019/6/19 10:41
 * @Version: 1.0
 **/
@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public boolean addOne(Product product) {
        Product save = productRepository.save(product);
        System.out.println("save =" + save.toString());
        if (0 < save.getId()) {
            return true;
        }
        return false;
    }

    public Page<Product> queryByPage(Integer pageSize, Integer pn, Product product) {
        // 采用自带的page分页方法  也可以使用pagehelper
        Pageable pageable= PageRequest.of(pn - 1, pageSize, Sort.Direction.ASC, "id");

        Page<Product> pageList = productRepository.findAll(new Specification<Product>() {
            @Override
            public Predicate toPredicate(Root<Product> r, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Predicate productName = cb.conjunction();
                Predicate stock = cb.conjunction();
                if (null != product.getProductName()) {
                    productName = cb.like(r.get("productName").as(String.class), "%" + product.getProductName() + "%");
                }
                if (null != product.getStock()) {
                    stock = cb.between(r.get("stock").as(Integer.class), 0, product.getStock());
                }
                return cb.and(productName, stock);
            }
        }, pageable);
//        PageHelper.startPage(pn - 1, pageSize);
//        PageInfo<Product> pageInfo = new PageInfo<>(pageList);
        return pageList;
    }
}
